import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:io';
import 'package:file_picker/file_picker.dart';
import 'package:sqflite/sqflite.dart';
import '../models/db_helper.dart';
import 'package:path_provider/path_provider.dart';

class CasesPage extends StatefulWidget {
  const CasesPage({super.key});

  @override
  State<CasesPage> createState() => _CasesPageState();
}

class _CasesPageState extends State<CasesPage> {
  List<Map<String, dynamic>> _caseList = [];
  String _search = '';
  String _filter = '全部医案';
  final List<String> _filters = ['全部医案', '太阳病', '少阳病', '少阴病', '阳明病', '太阴病', '厥阴病'];

  @override
  void initState() {
    super.initState();
    _loadCases();
  }

  Future<void> _loadCases() async {
    final db = await DBHelper.database;
    final data = await db.query('case_record');
    setState(() {
      _caseList = data;
    });
  }

  List<Map<String, dynamic>> get _filteredList {
    List<Map<String, dynamic>> list = _caseList;
    if (_filter != '全部医案') {
      list = list.where((e) => (e['tags'] ?? '').contains(_filter.replaceAll('病', ''))).toList();
    }
    if (_search.isNotEmpty) {
      final q = _search.toLowerCase();
      list = list.where((e) =>
        (e['title'] ?? '').toLowerCase().contains(q) ||
        (e['symptoms'] ?? '').toLowerCase().contains(q) ||
        (e['prescription'] ?? '').toLowerCase().contains(q)
      ).toList();
    }
    return list;
  }

  void _onImport() async {
    FilePickerResult? result = await FilePicker.platform.pickFiles(type: FileType.custom, allowedExtensions: ['json']);
    if (result != null && result.files.single.path != null) {
      final file = File(result.files.single.path!);
      try {
        final content = await file.readAsString();
        final List<dynamic> data = json.decode(content);
        final db = await DBHelper.database;
        int success = 0;
        for (var item in data) {
          if (item is Map<String, dynamic>) {
            await db.insert('case_record', item, conflictAlgorithm: ConflictAlgorithm.replace);
            success++;
          }
        }
        await _loadCases();
        if (mounted) {
          showDialog(
            context: context,
            builder: (ctx) => AlertDialog(
              title: const Text('导入结果'),
              content: Text('成功导入 $success 条医案。'),
              actions: [TextButton(onPressed: () => Navigator.pop(ctx), child: const Text('关闭'))],
            ),
          );
        }
      } catch (e) {
        if (mounted) {
          showDialog(
            context: context,
            builder: (ctx) => AlertDialog(
              title: const Text('导入失败'),
              content: Text('文件解析或导入出错：\n$e'),
              actions: [TextButton(onPressed: () => Navigator.pop(ctx), child: const Text('关闭'))],
            ),
          );
        }
      }
    }
  }

  void _onExport() async {
    try {
      final exportList = _filteredList;
      final jsonStr = json.encode(exportList);
      final dir = await getApplicationDocumentsDirectory();
      final file = File('${dir.path}/case_export_${DateTime.now().millisecondsSinceEpoch}.json');
      await file.writeAsString(jsonStr);
      if (mounted) {
        showDialog(
          context: context,
          builder: (ctx) => AlertDialog(
            title: const Text('导出成功'),
            content: Text('已导出${exportList.length}条医案到：\n${file.path}'),
            actions: [TextButton(onPressed: () => Navigator.pop(ctx), child: const Text('关闭'))],
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        showDialog(
          context: context,
          builder: (ctx) => AlertDialog(
            title: const Text('导出失败'),
            content: Text('导出出错：\n$e'),
            actions: [TextButton(onPressed: () => Navigator.pop(ctx), child: const Text('关闭'))],
          ),
        );
      }
    }
  }

  void _openCaseDetail(Map<String, dynamic> caseData) {
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (_) => CaseDetailPage(caseData: caseData),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('医案管理'),
        backgroundColor: Colors.brown[50],
        elevation: 0,
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 搜索栏
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                decoration: BoxDecoration(
                  color: Colors.brown[50],
                  borderRadius: BorderRadius.circular(24),
                ),
                child: Row(
                  children: [
                    const Icon(Icons.search, color: Colors.brown),
                    const SizedBox(width: 8),
                    Expanded(
                      child: TextField(
                        decoration: const InputDecoration(
                          hintText: '搜索医案、症状、方剂...',
                          border: InputBorder.none,
                          isDense: true,
                        ),
                        style: const TextStyle(color: Colors.brown),
                        onChanged: (v) => setState(() => _search = v),
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 16),
              // 分类筛选
              SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: Row(
                  children: _filters.map((f) => Padding(
                    padding: const EdgeInsets.only(right: 8),
                    child: _CaseFilterChip(
                      label: f,
                      selected: _filter == f,
                      color: _colorForFilter(f),
                      onTap: () => setState(() => _filter = f),
                    ),
                  )).toList(),
                ),
              ),
              const SizedBox(height: 24),
              // 医案列表
              const Text('医案列表', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: Colors.brown)),
              const SizedBox(height: 16),
              ..._filteredList.map((e) => Padding(
                padding: const EdgeInsets.only(bottom: 12),
                child: _CaseItem(
                  title: e['title'] ?? '',
                  tags: (e['tags'] ?? '').split(','),
                  desc: e['symptoms'] ?? '',
                  date: e['date'] ?? '',
                  tagColor: _colorForFilter(_filter == '全部医案' ? (e['tags'] ?? '') : _filter),
                  onTap: () => _openCaseDetail(e),
                ),
              )),
              const SizedBox(height: 32),
              // 批量操作区
              const Text('批量操作', style: TextStyle(fontWeight: FontWeight.bold, color: Colors.brown)),
              const SizedBox(height: 12),
              Row(
                children: [
                  Expanded(
                    child: OutlinedButton.icon(
                      icon: const Icon(Icons.upload_file, color: Colors.brown),
                      label: const Text('导入医案', style: TextStyle(color: Colors.brown)),
                      style: OutlinedButton.styleFrom(
                        side: const BorderSide(color: Colors.brown),
                        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
                        padding: const EdgeInsets.symmetric(vertical: 16),
                      ),
                      onPressed: _onImport,
                    ),
                  ),
                  const SizedBox(width: 16),
                  Expanded(
                    child: OutlinedButton.icon(
                      icon: const Icon(Icons.download, color: Colors.brown),
                      label: const Text('导出医案', style: TextStyle(color: Colors.brown)),
                      style: OutlinedButton.styleFrom(
                        side: const BorderSide(color: Colors.brown),
                        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
                        padding: const EdgeInsets.symmetric(vertical: 16),
                      ),
                      onPressed: _onExport,
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  Color _colorForFilter(String f) {
    switch (f.replaceAll('病', '')) {
      case '太阳': return const Color(0xFFD2A06B);
      case '少阳': return const Color(0xFFF6D365);
      case '少阴': return const Color(0xFFB39DDB);
      case '阳明': return const Color(0xFF80CBC4);
      case '太阴': return const Color(0xFF90CAF9);
      case '厥阴': return const Color(0xFF8D6E63);
      default: return Colors.brown;
    }
  }
}

class _CaseFilterChip extends StatelessWidget {
  final String label;
  final bool selected;
  final Color color;
  final VoidCallback? onTap;
  const _CaseFilterChip({required this.label, this.selected = false, this.color = Colors.grey, this.onTap});

  @override
  Widget build(BuildContext context) {
    return ChoiceChip(
      label: Text(label, style: TextStyle(color: selected ? Colors.white : color)),
      selected: selected,
      selectedColor: color,
      backgroundColor: color.withAlpha((0.1 * 255).toInt()),
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
      onSelected: (_) => onTap?.call(),
    );
  }
}

class _CaseItem extends StatelessWidget {
  final String title;
  final List<String> tags;
  final String desc;
  final String date;
  final Color tagColor;
  final VoidCallback? onTap;
  const _CaseItem({required this.title, required this.tags, required this.desc, required this.date, required this.tagColor, this.onTap});

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: onTap,
      child: Card(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
        elevation: 1,
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Text(title, style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 15)),
                  const SizedBox(width: 8),
                  ...tags.map((t) => Container(
                    margin: const EdgeInsets.only(left: 4),
                    padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                    decoration: BoxDecoration(
                      color: tagColor.withAlpha((0.15 * 255).toInt()),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Text(t, style: TextStyle(fontSize: 12, color: tagColor)),
                  )),
                ],
              ),
              const SizedBox(height: 8),
              Text(desc, style: const TextStyle(color: Colors.black87)),
              const SizedBox(height: 8),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(date, style: const TextStyle(fontSize: 12, color: Colors.brown)),
                  const Icon(Icons.chevron_right, color: Colors.brown),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class CaseDetailPage extends StatelessWidget {
  final Map<String, dynamic> caseData;
  const CaseDetailPage({Key? key, required this.caseData}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(caseData['title'] ?? '医案详情'),
        backgroundColor: Colors.brown[50],
        elevation: 0,
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: ListView(
          children: [
            ...caseData.entries.map((e) => Padding(
              padding: const EdgeInsets.symmetric(vertical: 6),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text('${_fieldLabel(e.key)}：', style: const TextStyle(fontWeight: FontWeight.bold, color: Colors.brown)),
                  const SizedBox(width: 8),
                  Expanded(child: Text('${e.value ?? ''}')),
                ],
              ),
            )),
          ],
        ),
      ),
    );
  }

  String _fieldLabel(String key) {
    switch (key) {
      case 'id': return '编号';
      case 'title': return '标题';
      case 'source': return '来源';
      case 'date': return '日期';
      case 'author': return '作者';
      case 'patient_info': return '患者信息';
      case 'chief_complaint': return '主诉';
      case 'history': return '病史';
      case 'symptoms': return '症状';
      case 'signs': return '体征';
      case 'analysis': return '分析';
      case 'prescription': return '处方';
      case 'effect': return '疗效';
      case 'tags': return '标签';
      default: return key;
    }
  }
} 